package com.chenjiaru.thread.lock;

import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;

/*
 * CountDownLatchDemo ：闭锁java5后才出现的juc，只有所有线程的运算全部完成，当前运算才继续执行
 * 使用场景：比如我们想计算1加20000的和
 */
@Slf4j
public class CountDownLatchDemo {
    private static Integer count1 = 0;
    private static Integer count2 = 0;

    public static void main(String[] arr) {

        calculateBySingleThread();
        calculateByMultiThread();

    }

    /**
     * 单线程计算
     */
    private static void calculateBySingleThread() {
        LocalDateTime start = LocalDateTime.now();
        int sum = IntStream.range(1, 20001).sum();
        log.info("单线程耗时：{}，sum={}", Duration.between(start, LocalDateTime.now()).toMillis(), sum);
    }

    /**
     * 多线程计算（闭锁）
     */
    private static void calculateByMultiThread() {
        CountDownLatch latch = new CountDownLatch(2);

        LocalDateTime start = LocalDateTime.now();
        new Thread(() -> {
            try {
                count1 = IntStream.range(1, 10001).sum();
            } finally {
                latch.countDown();
            }
        }).start();

        new Thread(() -> {
            try {
                count2 = IntStream.range(10001, 20001).sum();
            } finally {
                latch.countDown();
            }
        }).start();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int sum = count1 + count2;
        log.info("多线程耗时：{}，sum={}", Duration.between(start, LocalDateTime.now()).toMillis(), sum);
    }


}




